/*
Designer   : Renyangang

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package pins

import (
	"fmt"
	"fpga-vboard/logger"
)

var pinInsts map[string]*SignalPin
var pinMaps []*PinMap
var slicePinMaps []*PinMap

func init() {
	ClearPins()
}

func ClearPins() {
	pinInsts = make(map[string]*SignalPin)
	pinMaps = make([]*PinMap, 0)
	slicePinMaps = make([]*PinMap, 0)
}

func MappingPin(pinMap *PinMap) {
	pinMaps = append(pinMaps, pinMap)
}

func SetMappingPins(pMaps []*PinMap) {
	pinMaps = pMaps
}

func PrintAllPins() {
	for _, v := range pinInsts {
		fmt.Printf("%v: %p \n", v.Name, v.Value)
	}
}

func MakeFullPinMapping() error {
	for _, v := range pinMaps {
		inputPin := GetPin(v.InputDevId, v.InputPinName)
		outputPin := GetPin(v.OutputDevId, v.OutputPinName)

		if inputPin == nil {
			return fmt.Errorf("MakePinMapping: pin %v not found", v.InputPinName)
		}
		if outputPin == nil {
			return fmt.Errorf("MakePinMapping: pin %v not found", v.OutputPinName)
		}
		if inputPin.BitSize == outputPin.BitSize && (v.PinBitPair == nil || (((v.PinBitPair.InputBitEnd - v.PinBitPair.InputBitStart + 1) == inputPin.BitSize) && (v.PinBitPair.OutputBitEnd-v.PinBitPair.OutputBitStart+1) == outputPin.BitSize)) {
			// full mapping
			// fmt.Printf("full mapping: %v: %v: %p \n", v.InputPinName, v.OutputPinName, inputPin.Value)
			outputPin.Value = inputPin.Value
		} else {
			slicePinMaps = append(slicePinMaps, v)
		}
	}
	return nil
}

func MappingPinBitValues() {
	for _, v := range slicePinMaps {
		inputPin := GetPin(v.InputDevId, v.InputPinName)
		outputPin := GetPin(v.OutputDevId, v.OutputPinName)
		for i := v.PinBitPair.InputBitStart; i <= v.PinBitPair.InputBitEnd; i++ {
			outputPin.Value.SetTo(v.PinBitPair.OutputBitStart+(i-v.PinBitPair.InputBitStart), inputPin.Value.Test(i))
		}
	}
}

func AddPin(devId int, w *PinDef) *SignalPin {
	wPinName := fmt.Sprintf("%v_%v", devId, w.Name)
	if pinInsts[wPinName] != nil {
		logger.WarningLog("AddWire: wire %v already exists", wPinName)
		return pinInsts[wPinName]
	}
	pinInsts[wPinName] = NewSignalPin(wPinName, w.BitSize)
	return pinInsts[wPinName]
}

func AddPins(devId int, w []*PinDef) []*SignalPin {
	if w == nil {
		return nil
	}
	var ret []*SignalPin
	for _, v := range w {
		ret = append(ret, AddPin(devId, v))
	}
	return ret
}

func GetPin(devId int, name string) *SignalPin {
	wPinName := fmt.Sprintf("%v_%v", devId, name)
	return pinInsts[wPinName]
}
